<template>
	<view class="container">
		<view class="form">
			<uni-forms ref="formRef" :model="form" :rules="rules" label-position="top">
				<uni-forms-item label="公告标题" name="noticeTitle" required>
					<uni-easyinput v-model="form.noticeTitle" placeholder="请输入公告标题" />
				</uni-forms-item>
				<uni-forms-item label="公告类型" name="noticeType" required>
					<xy-select v-model="form.noticeType" :data="sys_notice_type" placeholder="公告类型" />
				</uni-forms-item>
				<uni-forms-item label="内容" name="noticeContent" required>
					<xy-editor v-model="form.noticeContent" placeholder="请输入内容" />
				</uni-forms-item>
				<uni-forms-item label="状态" name="status" required>
					<xy-checkbox v-model="form.status" :data="sys_notice_status" />
				</uni-forms-item>
				<uni-forms-item>
					<button class="mini-btn xy-btn" type="primary" size="mini" @click="submitForm()">确认</button>
					<button class="mini-btn xy-btn" type="warn" size="mini" @click="cancel()">取消</button>
				</uni-forms-item>
			</uni-forms>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		listNotice,
		getNotice,
		delNotice,
		addNotice,
		updateNotice
	} from "@/pages_work/api/system/notice";
	const {
		proxy
	} = getCurrentInstance();
	const {
		sys_notice_status,
		sys_notice_type
	} = proxy.useDict("sys_notice_status", "sys_notice_type");

	/** 表单数据 */
	const form = ref({});

	/** 表单检验规则 */
	const rules = ref(proxy.uniappRules({
		noticeTitle: [{ required: true, message: "公告标题不能为空", trigger: "blur" }],
		noticeType: [{ required: true, message: "公告类型不能为空", trigger: "change" }]
	}))

	onLoad((params) => {
		uni.setNavigationBarTitle({
			title: params.title
		});
		if (params.noticeId == undefined || params.noticeId == null || params.noticeId == '') {} else {
			handleUpdate(params);
		}
	})

	/** 取消按钮 */
	const cancel = () => {
		uni.navigateBack()
	}

	/** 提交按钮 */
	const submitForm = () => {
		proxy.$refs["formRef"].validate().then(valid => {
			if (valid) {
				if (form.value.noticeId != undefined) {
					updateNotice(form.value).then(response => {
						proxy.$modal.msgSuccess("修改成功");
						setTimeout(uni.navigateBack, 1000);
					});
				} else {
					addNotice(form.value).then(response => {
						proxy.$modal.msgSuccess("新增成功");
						setTimeout(uni.navigateBack, 1000);
					});
				}
			}
		});
	};

	/** 修改角色 */
	const handleUpdate = (row) => {
		const noticeId = row.noticeId;
		getNotice(noticeId).then(response => {
			form.value = response.data;
		});
	}
	
	onUnload(() => {
		uni.$emit('update')
	})
	
</script>

<style lang="scss">
	@import "@/static/scss/work/form.scss";
</style>